﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using TrainingWorkshop.Models;
using System.Transactions;
namespace TrainingWorkshop.Presentation
{
    public partial class CourseList : System.Web.UI.Page
    {
        /// <summary>
        /// PageLoad Show all the Course Records int the gridview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridviewBind();
            }
        }

        /// <summary>
        /// Select the required records and show them in the gridview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SearchButton_Click(object sender, EventArgs e)
        {
            //judge the coursename
            string coursename = CourseNameTextBox.Text.Trim();
            string regPatten = "^[A-Za-z]+$";
            Regex reg = new Regex(regPatten);
            if (coursename == "")
                WarningLabel.Text = "Not null";
            if (coursename.Length > 10)
                WarningLabel.Text = "CourseName too long";
            if (!reg.Match(coursename).Success)
                WarningLabel.Text = "Please input proper CourseName";
            else
            {
                GridviewBind();
            }
        }

        /// <summary>
        /// CourseListGridView_RowDataBound bound data to dropdownlist when editing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CourseListGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                // for even columns the system set two state
                if (e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit) || e.Row.RowState == DataControlRowState.Edit)
                {
                    //bound teachername data to dropdownlist
                    if ((DropDownList)e.Row.FindControl("TeacherDropDownList") != null)
                    {
                        DropDownList TeacherDropdownlist = e.Row.FindControl("TeacherDropDownList") as DropDownList;
                        TeacherDropdownlist.Items.Clear();
                        TeacherDropdownlist.DataSource = cm.GetAllTeachers();
                        TeacherDropdownlist.DataTextField = "TeacherName";
                        TeacherDropdownlist.DataValueField = "TeacherId";
                        TeacherDropdownlist.DataBind();
                        //set the default value
                        string dv = ((HiddenField)e.Row.FindControl("TeacherHiddenField")).Value.ToString();
                        TeacherDropdownlist.Items.FindByText(dv).Selected = true;
                        for (int i = 0; i < TeacherDropdownlist.Items.Count; i++)
                        {
                            if (TeacherDropdownlist.Items[i].Value == dv)
                            {
                                TeacherDropdownlist.SelectedIndex = i;
                            }
                        }
                    }

                    //bound Level data to dropdownlist
                    if ((DropDownList)e.Row.FindControl("LevelDropDownList") != null)
                    {
                        DropDownList LevelDropdownlist = e.Row.FindControl("LevelDropDownList") as DropDownList;
                        LevelDropdownlist.Items.Clear();
                        LevelDropdownlist.DataSource = cm.GetAllLevels();
                        LevelDropdownlist.DataTextField = "LevelName";
                        LevelDropdownlist.DataValueField = "LevelId";
                        LevelDropdownlist.DataBind();
                        //set the default value
                        string dv = ((HiddenField)e.Row.FindControl("LevelHiddenField")).Value.ToString();
                        LevelDropdownlist.Items.FindByText(dv).Selected = true;
                        for (int i = 0; i < LevelDropdownlist.Items.Count; i++)
                        {
                            if (LevelDropdownlist.Items[i].Value == dv)
                            {
                                LevelDropdownlist.SelectedIndex = i;
                            }
                        }

                    }
                    //bound Status data to dropdownlist
                    if ((DropDownList)e.Row.FindControl("StatusDropDownList") != null)
                    {
                        DropDownList StatusDropdownlist = e.Row.FindControl("StatusDropDownList") as DropDownList;
                        bool status = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "CourseStatus"));
                        ListItem li1 = new ListItem("Open", "True");
                        if (status)
                        {
                            li1.Selected = true;
                        }
                        StatusDropdownlist.Items.Add(li1);
                        ListItem li2 = new ListItem("Closed", "False");
                        if (!status)
                        {
                            li2.Selected = true;
                        }
                        StatusDropdownlist.Items.Add(li2);
                    }
                }

                //Bind Javascript to confirm dialog
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label myLab = (Label)e.Row.FindControl("StatusLabel");
                    if (myLab.Text.Trim().ToLower() == "closed")
                        ((Button)e.Row.FindControl("ButtonDelete")).Attributes.Add("onclick", "return confirm('Are you sure to delete this?')");
                    else
                        ((Button)e.Row.FindControl("ButtonDelete")).Attributes.Add("onclick", "alert('Open course is not allowed delete！');return false;");
                }

            }
        }
        /// <summary>
        /// RowEditing edit the selected course
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CourseListGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            CourseListGridView.EditIndex = (int)e.NewEditIndex;
            GridviewBind();

        }

        /// <summary>
        /// RowDeleting delete the selected coloum based on the Id
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CourseListGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string Id = CourseListGridView.DataKeys[e.RowIndex].Value.ToString();
            Course cs = new Course();
            cs.CourseId = Convert.ToInt32(Id);
            cm.DeleteCourse(cs.CourseId);
            GridviewBind();

        }

        /// <summary>
        /// Update 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CourseListGridView_Update(object sender, GridViewUpdateEventArgs e)
        {
            //get data from the input panel
            Course course = new Course();
            course.CourseId = Convert.ToInt32(CourseListGridView.DataKeys[e.RowIndex].Value.ToString());
            course.CourseName = ((TextBox)this.CourseListGridView.Rows[e.RowIndex].FindControl("CourseNameEditTextBox")).Text.Trim();
            course.TeacherId = Convert.ToInt32(((DropDownList)this.CourseListGridView.Rows[e.RowIndex].FindControl("TeacherDropDownList")).SelectedItem.Value);
            course.LevelId = Convert.ToInt32(((DropDownList)this.CourseListGridView.Rows[e.RowIndex].FindControl("LevelDropDownList")).SelectedItem.Value);
            course.CourseStatus = Convert.ToBoolean(((DropDownList)this.CourseListGridView.Rows[e.RowIndex].FindControl("StatusDropDownList")).SelectedItem.Value);
            cm.UpdateCourse(course);
            this.CourseListGridView.EditIndex = -1;
            GridviewBind();
        }
        /// <summary>
        /// EditCancel change the column patten
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CourseListGridView_Cancel(object sender, GridViewCancelEditEventArgs e)
        {
            this.CourseListGridView.EditIndex = -1;//change from edit to scan
            GridviewBind();

        }
        /// <summary>
        /// SelectAll Select all courses to batch close courses
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SelectAllCheckBox_CheckedChanged(object sender, EventArgs e)
        {

            for (int i = 0; i < CourseListGridView.Rows.Count; i++)
            {
                CheckBox cbox = (CheckBox)CourseListGridView.Rows[i].FindControl("StatusCheckBox");
                if (SelectAllCheckBox.Checked == true)
                {
                    cbox.Checked = true;
                }
                else
                {
                    cbox.Checked = false;
                }
            }

            SelectAllCheckBox.Checked = false;//cancel the checked after select all

        }
        /// <summary>
        /// ChangeStatus batch change open to close
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ChangeStatusButton_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < CourseListGridView.Rows.Count; i++)
            {
                CheckBox cbox = (CheckBox)CourseListGridView.Rows[i].FindControl("StatusCheckBox");
                string str = ((Label)CourseListGridView.Rows[i].FindControl("StatusLabel")).Text.Trim();
                bool status;
                if (str == "Open")
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                if (cbox.Checked == true && status == true)
                {
                    Course course = new Course();
                    course.CourseId = Convert.ToInt32(CourseListGridView.DataKeys[i].Value);
                    course.CourseStatus = status;
                    cm.ChangeState(course);
                }
            }
            GridviewBind();
        }
        /// <summary>
        /// AllCourses 
        /// Show all the courses in database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AllCoursesCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (AllCoursesCheckBox.Checked)
            {
                AllCoursesCheckBox.Checked = false;
                CourseNameTextBox.Text = "";
                StatusRadioButtonList.SelectedValue = "True";
                GridviewBind();
            }
        }
        /// <summary>
        /// GridviewBind
        /// Bind the data to gridview in different situation
        /// </summary>
        protected void GridviewBind()
        {
            if (CourseNameTextBox.Text == "")
            {
                CourseListGridView.DataSource = cm.GetAllCourses();
                CourseListGridView.DataKeyNames = new string[] { "CourseId" };
                CourseListGridView.DataBind();
            }
            else
            {
                CourseListGridView.DataSource = cm.GetSelectedCourses(CourseNameTextBox.Text, Convert.ToBoolean(StatusRadioButtonList.SelectedValue));
                CourseListGridView.DataKeyNames = new string[] { "CourseId" };
                CourseListGridView.DataBind();
            }
        }

    }
}